package swu.cx.defineviewgroup

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup

class parentSolid:ViewGroup {
    private val space = 30
    constructor(context: Context,attr:AttributeSet):super(context,attr){}

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        //d对父容器进行预测量
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //获取父容器的尺寸
        val parentWidth = MeasureSpec.getSize(widthMeasureSpec)
        val parentHeight = MeasureSpec.getSize(heightMeasureSpec)
        //计算到底有多少行
        val row = childCount/2+childCount%2
        //计算每个子控件的宽高
        val childWidth = if (childCount==1) parentWidth-2*space else (parentWidth-3*space)/2
        val childHeight = (parentHeight-(row+1)*space)/row
        //获取每个子控件的MeasureSpec
        val childWidthSpec = MeasureSpec.makeMeasureSpec(childWidth,MeasureSpec.EXACTLY)
        val childHeightSpec = MeasureSpec.makeMeasureSpec(childHeight,MeasureSpec.EXACTLY)
        //测量每个子控件
        for (i in 0 until childCount){
            getChildAt(i).measure(childWidthSpec,childHeightSpec)
        }
    }
    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
            var left = space
            var top = space
            for (i in 0 until childCount){
                val child = getChildAt(i)
                child.layout(left,top,left+child.measuredWidth,top+child.measuredHeight)
                left = if (i%2==0) child.measuredWidth+2*space else space
               if (i%2!=0){
                   top+=child.measuredHeight+space
               }
            }
    }
}